<template>
  <div>
    <van-nav-bar title="明日头条-登录" />
    <div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="user.mobile"
          required
          name="mobile"
          label="手机号"
          placeholder="请输入您的手机号"
          :rules="[
            {
              required: true,
              message: '请填写正确的手机号',
              trigger: 'onChange',
              pattern: /^1[3-9]\d{9}$/,
            },
          ]"
        />
        <van-field
          v-model="user.code"
          required
          type="password"
          name="code"
          label="密码"
          placeholder="请输入6位的密码"
          :rules="[
            {
              required: true,
              message: '必须是6位的数字密码',
              trigger: 'onChange',
              pattern: /^\d{6}$/,
            },
          ]"
        />
        <!-- native-type 代表提交按钮 -->
        <div style="margin: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            :disabled="isLoading"
            :loading="isLoading"
            loading-text="登录中..."
            >登录</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api/index'
import { setToken } from '@/utils/token'
import { setStorage } from '@/utils/storage'
import { Toast } from 'vant'
import Notify from '@/ui/Notify'

export default {
  name: 'Login',
  data () {
    return {
      user: {
        mobile: '13888888888', // 手机号
        code: '246810' // 验证码(相当于密码-必须是246810后台规定死的)
      },
      isLoading: false // 登录按钮的加载状态
    }
  },
  methods: {
    // 提交方法(form整体通过验证才会触发)
    async onSubmit (values) {
      // console.log('submit', values)
      // console.log(this.user)
      // 状态设置为true
      this.isLoading = true

      try {
        const res = await loginAPI(this.user)
        // console.log(res)
        Toast.success('登陆成功')
        setToken(res.data.data.token)
        setStorage('refresh_token', res.data.data.refresh_token)
        // 跳转一定要写在最后->尽量最后执行
        // this.$router.push()  会产生历史记录，可以回退
        // this.$router.replace()  不会产生历史记录
        this.$router.replace({
          path: this.$route.query.path || '/layout/home'
        })
      } catch (err) {
        // Promise内ajax抛出错误,直接进入这里
        Notify({ type: 'danger', message: '手机号或密码错误' })
      }
      this.isLoading = false // 网络请求完成无论成功/报错， 把状态关掉
    }
  }
}
</script>

<style scoped lang="less"></style>
